import { login, logout, getInfo } from '@/api/sysUser'
import { getToken, setToken, removeToken, getRefreshToken, setRefreshToken, removeRefreshToken, setTokenTime, removeTokenTime } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { Notification } from 'element-ui'

const state = {
  token: getToken(),
  refreshToken: getRefreshToken(),
  name: '',
  avatar: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_REFRESH_TOKEN: (state, refreshToken) => {
    state.refreshToken = refreshToken
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, imageCode } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, imageCode: imageCode }).then(response => {
        if (response.code === 200) {
          Notification.success({
            title: '系统提示',
            message: '登录成功！'
          })
        } else {
          reject()
        }

        const { data } = response
        commit('SET_TOKEN', data.accessToken)
        setToken(data.accessToken)
        commit('SET_REFRESH_TOKEN', data.refreshToken)
        setRefreshToken(data.refreshToken)

        const { expiresIn, expiresType } = data
        const timestamp = new Date().getTime()
        let expire = 0
        // 将秒数转为毫秒数
        if (expiresType === 'second') {
          expire = expiresIn * 1000
        }
        // 将分钟转为毫秒数
        if (expiresType === 'minute') {
          expire = expiresIn * 60 * 1000
        }
        // 保存token过期时间
        setTokenTime(timestamp + expire)

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('验证信息失败，请重新登录！')
        }

        const { name, avatar, roles } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('角色不能为空，请授权登录！')
        }

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_ROLES', roles == null ? ['Dashboard'] : roles)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        dispatch('tagsView/delAllViews', null, { root: true })
        commit('SET_TOKEN', '')
        commit('SET_REFRESH_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        removeRefreshToken()
        removeTokenTime()
        resetRouter()
        Notification.success({
          title: '系统提示',
          message: '退出成功！'
        })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_REFRESH_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      removeRefreshToken()
      removeTokenTime()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
